//
//  ManagerLoctaionViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/18.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ManagerLoctaionViewController.h"
#import "MLoctionCell.h"
#import "AddLoctionViewController.h"

@interface ManagerLoctaionViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation ManagerLoctaionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [NSMutableArray array];
      [self tableViewAndHeaderView];
//    [self initRightBarItem];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)initRightBarItem{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame=CGRectMake(0, 0, 20, 15);
    [rightButton setImage:[UIImage imageNamed:@"nav_xinxi_nor"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem =rightButton;
}


-(void)rightAction{
    
    
}

-(void)loadData{
    // 2.52查看收货地址
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              };
        __weak typeof(self)  weakSelf = self;
    [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:SELECTRECADDRESS paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
          DLog(@"查看收货地址接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *data = resultDic[@"data"];
            if([data isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            if(weakSelf.dataSource.count){
                [weakSelf.dataSource removeAllObjects];
            }
            for(NSDictionary *dic in data){
                LocationModel *model = [[LocationModel alloc]init];
                model.recId = dic[@"recId"];
                model.receiverName =dic[@"recName"];
                model.receiverAddress = dic[@"recAdres"];
                model.receiverPhone = dic[@"recPhone"];
                model.isDefault = dic[@"isDefault"];
                [weakSelf.dataSource addObject:model];
            }
            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            [MBProgressHUD dismissHUD];
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-49) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = [UIColor colorWithRed:242./255 green:242./255 blue:242./255 alpha:1.];

    _tableV.delegate = self;
    _tableV.dataSource =self;
    _tableV.separatorStyle =UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableV];
    _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.hidden = YES;
  }


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"actell";
    MLoctionCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"MLoctionCell" owner:self options:nil]lastObject];
    }
    LocationModel *model = self.dataSource[indexPath.row];
    __weak typeof(self)  weakSelf = self;
    cell.defultAddressBlock = ^(){
        // 2.54默认地址的选择
        NSDictionary *paraDic = @{
                                  @"uid":USERID,
                                  @"recAdrId":model.recId
                                  };
        [Tools AFNetworkingRequestTypePostWithUrl:SELECTDEFALTADR paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
                DLog(@"默认地址的选择---%@",resultDic);
            if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSDictionary *dataDic = resultDic[@"data"];
                if([dataDic isKindOfClass:[NSNull class]]) return ;
                    if(dataDic[@"status"]){
                    model.isDefault = @"1";
                   [weakSelf loadData];
                }
            }
        }];
};
    
    cell.deleteAddressBlock =^(){
        // 2.56删除收货地址接口
        NSDictionary *paraDic = @{
                                  @"userId":USERID,
                                  @"recAdrId":model.recId
                                  };
        [Tools AFNetworkingRequestTypePostWithUrl:DELETERECADR paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
            DLog(@"删除收货地址接---%@",resultDic);
            if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSDictionary *dataDic = resultDic[@"data"];
                if([dataDic isKindOfClass:[NSNull class]]) return;
                if([dataDic[@"status"] isEqualToString:@"true"]){
                [MBProgressHUD showTipMessageInWindow:@"删除成功"];
                //回到主线程刷新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.dataSource.count) {
                        [self.dataSource removeObjectAtIndex:indexPath.row];
                        DLog(@"删除了 %ld", indexPath.row);
                        if(self.dataSource.count==0){
                            self.tableV.hidden = YES;
                            return ;
                        }
                        if (indexPath.row== self.dataSource.count) {
                            // 删除的是最后一个直接刷新  并不是说数组中只有一个了 而是删除的位置区别  最后一个和非最后一个
                            [self.tableV reloadData];
                        }else{
//                            // 删除其他的cell，带动画
                            [self.tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            [self.tableV reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                            [self.tableV reloadData];
                        }
                    }
                });
                }else{
                    if(dataDic[@"errorString"]){
                        [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                    }
                }
            }else{
                if(resultDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
                }

            }
        }];
    };
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 133;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.isChangReceiveAddress){
        LocationModel *model = self.dataSource[indexPath.row];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changeReceiveAddress" object:model];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//新增收货地址
- (IBAction)addAddress:(id)sender {
    AddLoctionViewController *addLocation = [[AddLoctionViewController alloc]init];
    addLocation.vcName = @"新增收获地址";
    addLocation.isAddVC = YES;
    [self.navigationController pushViewController:addLocation animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
